'use strict';

const Controller = require('egg').Controller;

class UserController extends Controller {

  async createUser() {

    const ctx = this.ctx;
    const random = Math.round(Math.random(100) * 100);
    const userData = {
      name: 'xxxxx_' + random,
      age: random,
    };

    const user = await ctx.model.User.create(userData);
    ctx.status = 201;
    ctx.body = user;
  }


  async users() {
    const ctx = this.ctx;

    // this.ctx.throw(404, 'oono');

    const users = await ctx.model.User.findAll({
      limit: 10,
      offset: 0,
      order: [
        [ 'id', 'desc' ],
      ],
    });

    ctx.body = users;

  }


  async findOne() {
    const ctx = this.ctx;
    const id = ctx.params.id || 1;
    const one = await ctx.model.User.findByPk(id) || {};

    ctx.body = one;

  }

  async delete() {
    const ctx = this.ctx;
    const id = ctx.params.id || 0;

    let msg = { message: 'delete ok' };
    if (id == 0) {
      msg = { message: 'param id is empty..' };
    } else {
      const user = await ctx.model.User.findByPk(id);
      if (!user) { ctx.status = 404; return; }
      await user.destroy();
    }
    ctx.body = msg;
  }


  async update() {
    const ctx = this.ctx;
    const id = parseInt(ctx.params.id) || 0;
    const user = await ctx.model.User.findByPk(id) || '';

    if (!user) {
      ctx.body = 'param id is not correct';
      // setInterval(function() {
      //     ctx.redirect('/')
      // }, 3000)
      return;
    }
    const res = await user.update({
      name: 'test-test',
      id,
    });
    ctx.body = { message: 'update ok..' };
  }


}

module.exports = UserController;
